<?php
require_once __DIR__."/Base_model.php";
class Host_type_sub_model extends Base_model
{
    public function __construct()
    {
        parent::__construct();
        $this->table = "type_sub";
        $this->table1 = "type";
        $this->table2 = "biaoqian";
        $this->table3 = "user_material";
        $this->table4 = "quality_video";
        $this->table5 = "video";
    }

    /**
     * 查询话题库首页
     */
    public function all($arr)
    {
        $this->db->select('*');
        $this->db->from($this->table);
        //不是空的上下线状态
        if (!empty($arr['online'])) {
            $this->db->where("online", $arr['online']);
        }
        //不是空的分类筛选
        if (!empty($arr['join_type'])) {
            $this->db->where("sub_type", $arr['join_type']);
        }
        //分页
        if (!empty($arr['page']) && !empty($arr['limit'])) {
            $pages = ($arr['page'] - 1) * $arr['limit'];
            $datas['total'] = $this->db->count_all_results("", false);
            $this->db->limit($arr['limit'], $pages);
        } else {
            $datas['total'] = $this->db->count_all_results("", false);
        }

        //

        $this->db->order_by("(sort-0)","asc");
        $this->db->order_by('add_times', "desc");

        $res = $this->db->get();
        $datas['row'] = $res->result_array();
//        echo $this->db->last_query();
        return $datas;
    }

    /**
     * 话题列表查询
     * author: long
     * @param $arr 频道拥有的话题
     * @param array $where
     * @param string $order
     * @return
     */
    public function get_list($arr,$where = [], $order = '')
    {
        $hasArr = [];
        if(!empty($arr)){
            foreach ($arr as $k=>$v){
                $hasArr[] = $v['typesub_id'];
            }
        }
        // print_r($hasArr);
        $this->db->select('*');
        $this->db->from($this->table);
        if (!empty($where)) {
            $this->db->where($where);
        }
        if(!empty($arr)){
            $this->db->where_not_in('id',$hasArr);
        }
        if(!empty($order)){
            $this->db->order_by($order);
        }else{
            $this->db->order_by('id desc');
        }
        $res = $this->db->get();
        $rows = $res->result_array();

        // echo $this->db->last_query();
        return $rows;
    }

    /**
     * 查询用户列表下的该分类
     */
    public function all_type_sub($table, $arr)
    {
        $this->db->select("*");
        $this->db->from($table);
        $this->db->where(["join_type_sub" => $arr['join_type_sub']]);
        if (empty($arr['is_other'])) {
            $this->db->where("examine", 3);
        }

        //分页
        if (!empty($arr['page']) && !empty($arr['limit'])) {
            $pages = ($arr['page'] - 1) * $arr['limit'];
            $datas['total'] = $this->db->count_all_results("", false);
            $this->db->limit($arr['limit'], $pages);
        } else {
            $datas['total'] = $this->db->count_all_results("", false);
        }
        $this->db->order_by('type_sub_order', "asc");
        $this->db->order_by('add_time', "desc");
        $res = $this->db->get();
        $datas['row'] = $res->result_array();
//        echo $this->db->last_query();
        return $datas;
    }

    /**
     * 下线话题，开启事物操作
     */
    public function down_online($id)
    {
        //先根据分类id去查询user_material表所有该分类的
        $this->db->select('*');
        $this->db->from($this->table3);
        $this->db->where("join_type_sub", $id);
        $res = $this->db->get();
        $datas = $res->result_array();

        //判断是否为空
        if (!empty($datas)) {
            //查询出其它分类的ID
            $other = $this->is_other_id();
            $this->db->trans_begin();// 开启事务

            //添加
            foreach ($datas as $k => $v) {
                $data["join_type_sub"] = $other['id'];
                $data["examine"] = 1;
                $data["quality_order"] = 999999999;
                $data["type_sub_order"] = 999999999;
                $data["old_join_type_sub"] = $v['join_type_sub'];
                $this->db->update($this->table3, $data, ['id' => $v['id']]);
            }
            //受影响的行数
            $arr = $this->db->affected_rows();
            $this->db->update($this->table, ["online" => 1, "sort" => 999999999], ["id" => $id]);
            if ($this->db->trans_status() === false || $arr == 0) {
                $this->db->trans_rollback();//回滚
                return false;
            } else {
                $this->db->trans_commit();//提交事物
                return true;
            }


        } else {
            //为空直接修改状态就行
            return $this->db->update($this->table, ["online" => 1, "sort" => 999999999], ["id" => $id]);
        }
    }

    /**
     * 所属话题里移出话题开启事物操作
     */
    public function update_material($video_uuid)
    {
        //1.先去查询精品表是否有这个数据
        $re=$this->one($this->table4,["user_material_id" => $video_uuid]);
        if(!empty($re)){
            //2.先去修改精品表的
            $this->db->trans_begin();// 开启事务
            //先修改
            $datas['quality_join_type'] =1;
            $datas['quality_join_type_sub'] =1;
            $datas['online'] =1;
            $this->db->update($this->table4, $datas, ["user_material_id" => $video_uuid]);
            //受影响的行数
            $arr = $this->db->affected_rows();
            //删除
            $data['join_type']=1;
            $data['join_type_sub']=1;
            $data['quality_order']=999999999;
            $data['quality_order']=999999999;
            $data['examine']=1;
            $this->db->update($this->table3, $data, ['id' => $video_uuid]);

            if ($this->db->trans_status() === false || $arr == 0) {
                $this->db->trans_rollback();//回滚
                return false;
            } else {
                $this->db->trans_commit();//提交事物
                return true;
            }
        }else{
            $data['join_type']=1;
            $data['join_type_sub']=1;
            $data['quality_order']=999999999;
            $data['quality_order']=999999999;
            $data['examine']=1;
            $r2=$this->db->update($this->table3, $data, ['id' => $video_uuid]);
            if($r2){
                return true;
            }else{
                return false;
            }
        }

    }

    /**
     * 更改话题里的数据
     */
    public function save_edit_sort($data,$id){
        //1.先去这个数据在精品视频表里是否有数据
        $this->db->select("*");
        $this->db->from($this->table4);
        $this->db->where("user_material_id",$id);
        $res = $this->db->get();
        $data1 = $res->row_array();
        if(!empty($data1)){
            //2.如果有这个数据先去改精品视频表的数据
            $this->db->trans_begin();// 开启事务
            $datas['quality_join_type']=$data['join_type'];
            $datas['quality_join_type_sub']=$data['join_type_sub'];
            $datas['quatily_pic']=$data['pic'];
            $this->db->update($this->table4, $datas, ['user_material_id' => $id]);
            //受影响的行数
            $arr = $this->db->affected_rows();
            //修改用户上传表
            $this->db->update($this->table3, $data, ['id' => $id]);

            if ($this->db->trans_status() === false || $arr == 0) {
                $this->db->trans_rollback();//回滚
                return false;
            } else {
                $this->db->trans_commit();//提交事物
                return true;
            }
        }else{
            return $this->db->update($this->table3, $data, ['id' => $id]);
        }
    }

    /**
     * 更改其他话题里的数据
     */
    public function save_edit_sorts($data,$id){
        //1.先去这个数据在精品视频表里是否有数据
        $this->db->select("*");
        $this->db->from($this->table4);
        $this->db->where("user_material_id",$id);
        $res = $this->db->get();
        $data1 = $res->row_array();
        if(!empty($data1)){
            //2.如果有这个数据先去改精品视频表的数据
            $this->db->trans_begin();// 开启事务
            $datas['online']=2;
            $datas['quality_join_type']=$data['join_type'];
            $datas['quality_join_type_sub']=$data['join_type_sub'];
            $this->db->update($this->table4, $datas, ['user_material_id' => $id]);
            //受影响的行数
            $arr = $this->db->affected_rows();
            //修改用户上传表
            $this->db->update($this->table3, $data, ['id' => $id]);

            if ($this->db->trans_status() === false || $arr == 0) {
                $this->db->trans_rollback();//回滚
                return false;
            } else {
                $this->db->trans_commit();//提交事物
                return true;
            }
        }else{
            return $this->db->update($this->table3, $data, ['id' => $id]);
        }
    }

    /**
     * 查询分类
     */
    public function types($type = 1)
    {
        $this->db->select('*');
        $this->db->from($this->table1);
        if ($type == 1) {
            $this->db->where("is_other !=", 999999999);
            $this->db->where("online", 2);
        }else if($type == 2){
            $this->db->where("online", 2);
        }
        $res = $this->db->get();
        $datas = $res->result_array();
//        echo $this->db->last_query();
        return $datas;
    }

    /**
     * 查询话题
     */
    public function type_sub($where = [], $type = 1)
    {
        $this->db->select('*');
        if ($type == 1) {
            $this->db->from($this->table2);
        } else if ($type == 2) {
            $this->db->from($this->table);
        } else if ($type == 3) {
            $this->db->from($this->table);
        }else if ($type == 4) {
            $this->db->from($this->table);
        }
        //这是不加入已挑选视频
        if ($type == 1 || $type == 4) {
            $this->db->where("online", 2);
            $this->db->where($where);
        } else if ($type == 3) {
            $this->db->where("online", 2);
        }
        $res = $this->db->get();
        $datas = $res->result_array();
//        echo $this->db->last_query();
        return $datas;
    }

    /**
     * 查询话题表中is_other为999999999的id
     */
    public function is_other_id()
    {
        $this->db->select('*');
        $this->db->from($this->table);
        $this->db->where("is_other", 999999999);
        $res = $this->db->get();
        $datas = $res->row_array();
//        echo $this->db->last_query();
        return $datas;
    }

    /**
     * 查询所有精品列表数据
     */
    public function get_table($arr)
    {
        $this->db->select('*');
        $this->db->from($this->table4);

        $this->db->where("online", 2);
        $this->db->where("del3", 2);
        $this->db->where("is_join !=", 2);
        $this->db->where("quality_join_type_sub", $arr['type_id']);
        //分页
        if (!empty($arr['page']) && !empty($arr['limit'])) {
            $pages = ($arr['page'] - 1) * $arr['limit'];
            $datas['total'] = $this->db->count_all_results("", false);
            $this->db->limit($arr['limit'], $pages);
        } else {
            $datas['total'] = $this->db->count_all_results("", false);
        }

        //
        $this->db->order_by('add_time', "desc");
        $res = $this->db->get();
        $datas['row'] = $res->result_array();
//        echo $this->db->last_query();
        return $datas;
    }

    /**
     * 加入话题
     */
    public function update_table($arr)
    {
        $a = [];
        foreach ($arr as $kk => $vv) {
            $re = $this->one("quality_video", ["id" => $vv]);
            $a[] = $re;
        }
        foreach ($a as $k => $v) {
            //拼接添加到用户投稿列表的数据
            $datas['uuid'] = $v['uuid'];
            $datas['nick_name'] = $v['nick_name'];
            $datas['nick_pic'] = $v['nick_pic'];
            $datas['video_uuid'] = $v['quality_uuid'];
            $datas['mix_status'] = 1;
            $datas['pic'] = $v['quatily_pic'];
//            $datas['title'] = $v['title'];
            $datas['join_type'] = $v['quality_join_type'];
            $datas['join_type_sub'] = $v['quality_join_type_sub'];
            $datas['video_url'] = $v['quality_video_url'];
            $datas['video_desc'] = $v['quality_desc'];
            $datas['examine'] = 3;
            $datas['type'] = 1;
            $datas['quality'] = 1;
            $datas['add_time'] = date("Y-m-d H:i:s", time());
            $this->db->trans_begin();// 开启事务
            //添加
            $this->db->insert($this->table3, $datas);
            $user_material_id = $this->db->insert_id();
            //受影响的行数
            $arr = $this->db->affected_rows();

            $data['user_material_id'] = $user_material_id;
            $data['is_join'] = 2;
            $data['online'] = 2;
            //添加
            $id = $this->db->update($this->table4, $data, ['id' => $v['id']]);
            if ($this->db->trans_status() === false || $arr == 0) {
                $this->db->trans_rollback();//回滚
                return false;
            } else {
                $this->db->trans_commit();//提交事物
            }
        }

        return true;

    }

    /**
     * 上线话题
     */
    public function up_words($video_uuid){
        //1.先去查询原始素材中属于这个话题的(video表)
        $this->db->select('video_id,old_video_type');
        $this->db->from($this->table5);
        $this->db->where("video_join_sub", $video_uuid);
        $res1 = $this->db->get();
        $data1= $res1->result_array();

        //2.再去查原始素材表(user_material表)
        $this->db->select('id,old_examine');
        $this->db->from($this->table3);
        $this->db->where("join_type_sub", $video_uuid);
        $res2 = $this->db->get();
        $data2= $res2->result_array();

        //3.修改
        $datas1=[];
        $datas2=[];
        $this->db->trans_begin();// 开启事务
        if(!empty($data1)){
            foreach($data1 as $k=>$v){
                $datas1['video_type']=$v['old_video_type'];
//                $datas1['old_video_type']="";
                $this->db->update($this->table5,$datas1,['video_id'=>$v['video_id']]);
            }
        }
        if(!empty($data2)){
            foreach($data2 as $kk=>$vv){
                $datas2['examine']=$vv['old_examine'];
//                $datas2['old_examine']="";
                $this->db->update($this->table3,$datas2,['id'=>$vv['id']]);
            }
        }
        $arr=$this->db->affected_rows();//受影响的行数
        //4.再去修改这个话题下线状态
        $this->db->update($this->table,['online'=>2],["id"=>$video_uuid]);
        if($this->db->trans_status()===false || $arr==0){
            $this->db->trans_rollback();//回滚
            return false;
        }else{
            $this->db->trans_commit();//提交事物
            return true;
        }
    }

    /**
     * 下线话题
     */
    public function down_words($video_uuid){
        //先去查出话题is_other为999999999的
        $qita=$this->one($this->table,['is_other'=>999999999]);
        //1.先去查询原始素材中属于这个话题的(video表)
        $this->db->select('video_id,video_type');
        $this->db->from($this->table5);
        $this->db->where("video_join_sub", $video_uuid);
        $res1 = $this->db->get();
        $data1= $res1->result_array();

        //2.再去查用户素材表(user_material表)
        $this->db->select('id,examine');
        $this->db->from($this->table3);
        $this->db->where("join_type_sub", $video_uuid);
        $res2 = $this->db->get();
        $data2= $res2->result_array();

        //3.再去精品视频表查这个（quality_video）
        $this->db->select('id,user_material_id');
        $this->db->from($this->table4);
        $this->db->where("quality_join_type_sub", $video_uuid);
        $res3 = $this->db->get();
        $data3= $res3->result_array();
        //4.修改
        $datas1=[];
        $datas2=[];
        $datas3=[];
//        $this->db->trans_begin();// 开启事务
        if(!empty($data1)){
            //5.这是原始素材表修改
            foreach($data1 as $k=>$v){
                $datas1['video_type']=1;
                $datas1['video_join_type']=$qita['sub_type'];
                $datas1['video_join_sub']=$qita['id'];
                $datas1['drop_time']=date("Y-m-d H:i:s",time());
                $this->db->update($this->table5,$datas1,['video_id'=>$v['video_id']]);
            }
        }
        if(!empty($data2)){
            //6.这是用户素材表修改
            foreach($data2 as $kk=>$vv){
                //6.1先去查出每一个用户素材的信息
                $user_material=$this->one($this->table3,['id'=>$vv['id']]);
                $datas2['examine']=1;
                $datas2['old_join_type_sub']=$user_material['join_type_sub'];
                $datas2['old_join_type']=$user_material['join_type'];
                $datas2['join_type']=$qita['sub_type'];
                $datas2['join_type_sub']=$qita['id'];
                $this->db->update($this->table3,$datas2,['id'=>$vv['id']]);
            }
        }
        if(!empty($data3)){
            //7.这是精品视频表修改
            foreach($data3 as $kkk=>$vvv){
                $datas3['quality_join_type']=$qita['sub_type'];
                $datas3['quality_join_type_sub']=$qita['id'];
                $this->db->update($this->table4,$datas3,['id'=>$vvv['id']]);
            }
        }
//        $arr=$this->db->affected_rows();//受影响的行数
        //8.再去修改这个话题下线状态
        $this->db->update($this->table,['online'=>1,'sort'=>999999999],["id"=>$video_uuid]);
//        if($this->db->trans_status()===false || $arr==0){
//            $this->db->trans_rollback();//回滚
//            return false;
//        }else{
//            $this->db->trans_commit();//提交事物
//            return true;
//        }
        return true;
    }

    /**
     * 修改排序
     */
    public function update_sort($sort,$id,$old_sort){
        //1.先去查询所有排序为1-100的
        $this->db->select("id,sort");
        $this->db->from($this->table);
        $this->db->where("sort>=",1);
        $this->db->where("sort<=",100);
        $this->db->order_by('sort',"asc");
        $res1= $this->db->get();
        $data1 =$res1->result_array();
        if(!empty($data1)){
            //4.如果排序值小于已排序个数，把小于这个排序值的放入一个数组，从一开始依次排，大于这个排序的，放入另一个数组，从这个排序之后一次排
            $sort1 = [];
            $sort2 = [];
            $data2 = [];
            //4.原有排序值大于这个排序值的放入$sort2，小于的放入$sort1
            foreach ($data1 as $k => $v) {
                if ($v['sort'] < $sort && $v['sort'] != $old_sort) {
                    $sort1[] = $v['sort'];
                } else if ($v['sort'] >= $sort && $v['sort'] != $old_sort) {
                    $sort2[] = $v['sort'];
                } else {
                    //5.删除$data1中的值，方便遍历，用$data2遍历就行
                    unset($data1[$k]);
                }
            }
            foreach ($data1 as $a => $b) {
                $data2[] = $b;
            }
            $g1 = $this->s1($sort1);
            $g2 = $this->s2($sort2, $sort);
            $g3 = array_merge($g1, $g2);
            $sort3 = array_merge($sort1, $sort2);

            ///////////
            if (empty(array_diff_assoc($g3, $sort3))) {
                $res = $this->update($this->table, ['sort' => $sort], ['id' => $id]);
                if ($res) {
                    return true;
                } else {
                    return false;
                }

            } else {
                //先去把以前的排序值从1开始依次排序
                foreach ($data2 as $kk => $vv) {
                    $this->update($this->table, ['sort' => $g3[$kk]], ['id' => $vv['id']]);
                }
                //再去修改这个要排序的值
                $res = $this->update($this->table, ['sort' => $sort], ['id' => $id]);
                if ($res) {
                    return true;
                } else {
                    return false;
                }
            }
        }else{
            $res=$this->update($this->table,['sort'=>$sort],['id'=>$id]);
            if($res){
                return true;
            }else{
                return false;
            }
        }


    }

    /**
     * 修改所属话题排序
     */
    public function update_sort1($sort,$id,$old_sort,$join_type_sub){
        //1.先去查询所有排序为1-100的
        $this->db->select("id,type_sub_order");
        $this->db->from($this->table3);
        $this->db->where("type_sub_order>=",1);
        $this->db->where("type_sub_order<=",100);
        $this->db->where("join_type_sub",$join_type_sub);
        $this->db->order_by('type_sub_order',"asc");
        $res1= $this->db->get();
        $data1 =$res1->result_array();
        if(!empty($data1)){
            //4.如果排序值小于已排序个数，把小于这个排序值的放入一个数组，从一开始依次排，大于这个排序的，放入另一个数组，从这个排序之后一次排
            $sort1 = [];
            $sort2 = [];
            $data2 = [];
            //4.原有排序值大于这个排序值的放入$sort2，小于的放入$sort1
            foreach ($data1 as $k => $v) {
                if ($v['type_sub_order'] < $sort && $v['type_sub_order'] != $old_sort) {
                    $sort1[] = $v['type_sub_order'];
                } else if ($v['type_sub_order'] >= $sort && $v['type_sub_order'] != $old_sort) {
                    $sort2[] = $v['type_sub_order'];
                } else {
                    //5.删除$data1中的值，方便遍历，用$data2遍历就行
                    unset($data1[$k]);
                }
            }
            foreach ($data1 as $a => $b) {
                $data2[] = $b;
            }
            $g1 = $this->s1($sort1);
            $g2 = $this->s2($sort2, $sort);
            $g3 = array_merge($g1, $g2);
            $sort3 = array_merge($sort1, $sort2);

            ///////////
            if (empty(array_diff_assoc($g3, $sort3))) {
                $res = $this->update($this->table3, ['type_sub_order' => $sort], ['id' => $id]);
                if ($res) {
                    return true;
                } else {
                    return false;
                }

            } else {
                //先去把以前的排序值从1开始依次排序
                foreach ($data2 as $kk => $vv) {
                    $this->update($this->table3, ['type_sub_order' => $g3[$kk]], ['id' => $vv['id']]);
                }
                //再去修改这个要排序的值
                $res = $this->update($this->table3, ['type_sub_order' => $sort], ['id' => $id]);
                if ($res) {
                    return true;
                } else {
                    return false;
                }
            }
        }else{
            $res=$this->update($this->table3,['type_sub_order'=>$sort],['id'=>$id]);
            if($res){
                return true;
            }else{
                return false;
            }
        }


    }

    public function s1($sort){
        if(!empty($sort)){
            $sort[0]=1;
            $len=count($sort);
            for($i=1;$i<$len;$i++){
                $sort[$i]=$sort[$i-1]+1;
            }
            return $sort;
        }else{
            return [];
        }
    }
    public function s2($sort1,$sort){
        if(!empty($sort1)){
            $sort1[0]=$sort+1;
            $len=count($sort1);
            for($i=1;$i<$len;$i++){
                $sort1[$i]=$sort1[$i-1]+1;
            }
            return $sort1;
        }else{
            return [];
        }
    }


    /**
     * 判断分类是否存在
     */
    public function one_save($where,$id){
        $this->db->select('*');
        $this->db->from($this->table);
        $this->db->where($where);
        $this->db->where('id!=',$id);
        $res = $this->db->get();
        $datas= $res->result_array();
//        echo $this->db->last_query();
        return $datas;
    }

















}